package utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;


/**
 * Execute command on system level
 * 
 * @author julien
 *
 */


public class SystemCommand {
	@SuppressWarnings("finally")
	static public String execute(String cmd) 
	{		
		
		System.out.println("SystemCommand execute() : "+ cmd);
		
		Process p = null;
		try{				
			Runtime r = Runtime.getRuntime();
			p = r.exec(cmd);
			p.waitFor();
			BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = "";

			while ((line = b.readLine()) != null) 
			{
			  System.out.println(line);
			}
		}
		catch(Exception e) 
		{
			System.err.println("SystemCommand.execute() : "+e.getMessage());
		}
		finally
		{
			// Obtain status and output
			int code = p.exitValue();
//			IOUtils.toString(inputStream, encoding)
			String  err = convertStreamToString(p.getErrorStream());//.getText();
			String input = convertStreamToString(p.getInputStream());//.getText(); // *out* from the external program is *in* for groovy

			System.out.println("return code: "+code);
			System.out.println("stderr: "+err);
			System.out.println("stdout: "+input);

			
			return cmd;
		}
	}
	
	public static String convertStreamToString(InputStream is) 
	{
	    Scanner s = new Scanner(is).useDelimiter("\\A");
	    return s.hasNext() ? s.next() : "";
	}

}
